<?php
/**
 * CONTENIDO extension pack (mpContenidoX), consists of multiple classes to
 * provide more features for Plugins/Modules.
 *
 * @package     mpContenidoX
 * @subpackage  PluginInstaller
 * @author      Murat Purc <murat@purc.de>
 * @copyright   Copyright (c) 2008-2012 Murat Purc (http://www.purc.de)
 * @license     http://www.gnu.org/licenses/gpl-2.0.html - GNU General Public License, version 2
 * @version     $Id: ContainerXml.class.php 21 2012-07-16 21:33:14Z purcaholic $
 */


defined('CON_FRAMEWORK') or die('Illegal call');


/**
 * Plugin install file reader for XML files.
 *
 * @package     mpContenidoX
 * @subpackage  PluginInstaller
 * @author      Murat Purc <murat@purc.de>
 */
class mpPluginInstaller_Reader_ContainerXml extends mpPluginInstaller_Reader_Abstract
{

    /**
     * SimpleXMLElement instance
     * @var SimpleXMLElement
     */
    private static $_xml = null;


    /**
     * Constructor
     * @param   string  $file
     * @return  void
     */
    public function __construct($file)
    {
        if (!is_file($file)) {
            throw new mpPluginInstaller_Exception("Missing file $file");
        }
        if (self::$_xml == null) {
            self::$_xml = new SimpleXMLElement($file, null, true);
        }
    }


    /**
     * Returns meta data.
     *
     * @return  mpPluginInstaller_MetaData
     */
    public function getMetaData()
    {
        if ($this->_metaData instanceof mpPluginInstaller_MetaData) {
            return $this->_metaData;
        }

        $this->_metaData = new mpPluginInstaller_MetaData();
        if ($result = self::$_xml->xpath('meta')) {
            foreach ($result[0] as $name => $value) {
                $this->_metaData->$name = (string) $value;
            }
        }

        return $this->_metaData;
    }


    /**
     * Returns dependencies
     *
     * @return  ArrayObject  Containing mpPluginInstaller_DependencyData instances
     */
    public function getDependencies()
    {
        $obj = new ArrayObject();
        if ($result = self::$_xml->xpath('dependencies/item')) {
            foreach ($result as $pos => $item) {
                $attr = $item->attributes();
                $dependency = new mpPluginInstaller_DependencyData((string) $attr->type);
                $dependency->setIdInternal((string) $attr->idinternal);
                $dependency->setVersion((string) $attr->version);
                $dependency->setUrl((string) $attr->url);
                $obj->append($dependency);
            }
        }
        return $obj;
    }

    public function getSQL($mode)
    {
        $this->_checkMode($mode);
        if ($result = self::$_xml->xpath($mode . '/sql')) {
            return $result[0];
        }
        return null;
    }

    public function getRessources($mode)
    {
        $this->_checkMode($mode);
        return self::$_xml->xpath($mode . '/ressources');
    }

}
